#!/bin/bash
cd "$(dirname "$0")/.."
source ./script/setup.sh

zip_uri='' # mandatory
cask_name='' # mandatory
conflicts_with_casks=''
build_version="0.0.0-SNAPSHOT"
out_dir='.release'
while [[ $# -gt 0 ]]; do
    case $1 in
        --build-version) build_version="$2"; shift 2 ;;
        --zip-uri) zip_uri="$2"; shift 2 ;;
        --out-dir) out_dir="$2"; shift 2 ;;
        --cask-name) cask_name="$2"; shift 2 ;;
        --conflicts-with-casks) conflicts_with_casks="$2"; shift 2 ;;
        *) echo "Unknown arg $1"; exit 1 ;;
    esac
done

if test -z "$zip_uri"; then echo "--zip-uri is mandatory" > /dev/stderr; exit 1; fi
if test -z "$cask_name"; then echo "--cask-name is mandatory" > /dev/stderr; exit 1; fi

zip_file=''
if test -f "$zip_uri"; then
    zip_file=$zip_uri
    zip_uri="file://$(realpath "$zip_file")"
elif grep -q '^http' <<< "$zip_uri"; then
    zip_file=/tmp/AeroSpace-tmp.zip
    rm -rf $zip_file
    curl -L "$zip_uri" -o $zip_file
else
    echo "$zip_uri doesn't exist" > /dev/stderr; exit 1
fi
sha=$(shasum -a 256 "$zip_file" | awk '{print $1}')

manpages=$(unzip -l "$zip_file" | \
    grep --only-matching 'manpage/aerospace-.*' | \
    while read -r it; do echo "  manpage \"AeroSpace-v$build_version/$it\""; done)

if ! test -z "$conflicts_with_casks"; then
    conflicts_with_casks="  conflicts_with cask: '$conflicts_with_casks'"
fi

cask_version=''
if grep -q SNAPSHOT <<< $build_version; then
    # Prevent 'Not upgrading aerospace, the latest version is already installed'
    cask_version=':latest'
else
    cask_version="'$build_version'"
fi

rm -f "$out_dir/$cask_name.rb" || true
mkdir -p "$out_dir"
cat > "$out_dir/$cask_name.rb" <<EOF
cask "$cask_name" do # THE FILE IS GENERATED BY build-brew-cask.sh
  version $cask_version
  sha256 "$sha"

  url "$zip_uri"
  name "AeroSpace"
  desc "AeroSpace is an i3-like tiling window manager for macOS"
  homepage "https://github.com/nikitabobko/AeroSpace"

$conflicts_with_casks

  depends_on macos: ">= :ventura" # macOS 13

  postflight do
    system "xattr -d com.apple.quarantine #{staged_path}/AeroSpace-v$build_version/bin/aerospace"
    system "xattr -d com.apple.quarantine #{appdir}/AeroSpace.app"
  end

  app "AeroSpace-v$build_version/AeroSpace.app"
  binary "AeroSpace-v$build_version/bin/aerospace"

  binary "AeroSpace-v$build_version/shell-completion/zsh/_aerospace",
      target: "#{HOMEBREW_PREFIX}/share/zsh/site-functions/_aerospace"
  binary "AeroSpace-v$build_version/shell-completion/bash/aerospace",
      target: "#{HOMEBREW_PREFIX}/etc/bash_completion.d/aerospace"
  binary "AeroSpace-v$build_version/shell-completion/fish/aerospace.fish",
      target: "#{HOMEBREW_PREFIX}/share/fish/vendor_completions.d/aerospace.fish"

$manpages
end
EOF
